package com.takeoff.iot.modbus.netty.message;

import java.util.Arrays;

import com.takeoff.iot.modbus.common.bytes.factory.ModbusDataFactory;
import com.takeoff.iot.modbus.common.data.ModbusData;
import com.takeoff.iot.modbus.common.message.ModbusMessage;
import com.takeoff.iot.modbus.common.utils.IntegerToByteUtil;
import com.takeoff.iot.modbus.common.utils.ModbusCrc16Utils;

import org.apache.commons.lang3.ArrayUtils;
import org.bouncycastle.util.encoders.Hex;

import io.netty.handler.codec.DecoderException;

/**
 * 类功能说明：对接收到的指令数据进行校验<br/>
 * 公司名称：TF（腾飞）开源 <br/>
 * 作者：luorongxi <br/>
 */
public class ModbusInMessage implements ModbusMessage {

	private String deviceGroup;
	private byte[] msg;
	private ModbusData data;

	public ModbusInMessage(byte[] msg, ModbusDataFactory dataFactory){
		this(null, msg, dataFactory);
	}

	public ModbusInMessage(String channelName, byte[] msg, ModbusDataFactory dataFactory){
		this.deviceGroup = channelName;
		this.msg = msg;
		//TODO 校验上传上来的数据内容
		byte[] datas = msg;
		int command = msg[FUNC_INDEX];;
		this.data = dataFactory.buildData(command, datas);
//		System.out.println("MiiInMessage 38 data: " + Hex.toHexString(data.toBytes()));
	}

	public String deviceGroup() {
		return deviceGroup;
	}

	public int command() {
		return msg[FUNC_INDEX];
	}

	public int length() {
//		byte[] dataLength = ArrayUtils.subarray(msg, DATA_INDEX, COMMAND_INDEX);
//		return IntegerToByteUtil.bytesToInt(dataLength);
		return msg.length;
	}

	public ModbusData data() {
		return data;
	}

	public int type() {
		return ModbusMessage.READ;
	}

	public byte[] toBytes() {
		return msg;
	}
}
